package com.example.light.web.system.controller;

import com.example.light.common.GlobalConstant;
import com.example.light.common.exception.GlobalException;
import com.example.light.common.result.CodeMsg;
import com.example.light.common.result.Result;
import com.example.light.redis.RedisService;
import com.example.light.redis.UserKey;
import com.example.light.web.system.entity.User;
import com.example.light.web.system.service.UserService;
import com.example.light.web.system.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    /**
     * 用户注册
     *
     * @param loginVO
     * @return
     */
    @RequestMapping("register")
    @ResponseBody
    public Result<Boolean> register(LoginVO loginVO) {
        if (loginVO == null) {
            throw new GlobalException(CodeMsg.SystemCodeMsg.USER_NON);
        }
        boolean succ = userService.register(loginVO);
        if (succ) {
            return Result.success(true);
        }
        return Result.error(CodeMsg.SystemCodeMsg.ERROR);
    }

    @RequestMapping("login")
    @ResponseBody
    public Result<User> login(LoginVO loginVO, HttpServletResponse response) {
        User loginSucc = userService.login(loginVO, response);
        if (null != loginSucc) {
            return Result.success(loginSucc);
        }
        return Result.error(CodeMsg.SystemCodeMsg.ERROR);
    }

    @RequestMapping("logout")
    public String logout(HttpSession session, HttpServletRequest request) {
        session.invalidate();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            // cookie失效
            if(cookie.getName().equalsIgnoreCase(GlobalConstant.COOKIE_NAME)){
                redisService.delete(UserKey.token,cookie.getValue());
                cookie.setMaxAge(-1);
            }
        }
        return "login";
    }


}
